<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发票管理系统</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div class="container">
        <!-- 上传模块 -->
        <div class="card">
            <h2>发票上传</h2>
            <input type="file" id="uploadInput" accept="image/*">
            <button onclick="uploadFile()">上传发票</button>
        </div>

        <!-- 查询模块 -->
        <div class="card">
            <h2>发票查询</h2>
            <div class="filters">
                <input type="date" id="startDate">
                <input type="date" id="endDate">
                <input type="text" id="searchKey" placeholder="输入关键字">
                <button onclick="loadData()">查询</button>
                <input type="text" id="naturalQuery" placeholder="输入自然语言查询">
                <button onclick="naturalLanguageQuery()">自然语言查询</button>
            </div>
            <div id="resultList"></div>
        </div>

        <!-- 统计模块 -->
        <div class="card stats">
            <h2>统计信息</h2>
            <div class="stat-item">
                <span>总张数：</span>
                <span id="totalCount">0</span>
            </div>
            <div class="stat-item">
                <span>总金额：</span>
                <span id="totalAmount">0.00</span>
            </div>
        </div>

        <!-- 图片预览 -->
        <div id="previewModal" class="modal">
            <span class="close" onclick="closePreview()">&times;</span>
            <img class="modal-content" id="previewImage">
        </div>
    </div>

    <script>
        // 文件上传
        async function uploadFile() {
            const fileInput = document.getElementById('uploadInput');
            if (!fileInput.files[0]) {
                alert('请选择文件');
                return;
            }

            const formData = new FormData();
            formData.append('file', fileInput.files[0]);

            try {
                const response = await fetch('http://localhost:5000/upload', {
                    method: 'POST',
                    body: formData
                });
                const result = await response.json();
                console.log("后端返回的响应数据:", result);

                if (result.message) {
                    alert(result.message);
                    loadData();
                } else if (result.error) {
                    alert(result.error);
                }
            } catch (error) {
                alert('上传失败');
            }
        }

        // 加载数据
        async function loadData() {
            /*const params = new URLSearchParams({
                start: document.getElementById('startDate').value,
                end: document.getElementById('endDate').value,
                keyword: document.getElementById('searchKey').value
            });*/
            const start = document.getElementById('startDate').value;
            const end = document.getElementById('endDate').value;
            const keyword = document.getElementById('searchKey').value;
            console.log('开始日期:', start);
            console.log('结束日期:', end);
            console.log('关键字:', keyword);
            const params = new URLSearchParams({
                start,
                end,
                keyword
            });
            try {
                // 加载列表
                const listRes = await fetch(`http://localhost:5000/query?${params}`);
                if (!listRes.ok) {
                    throw new Error(`请求列表数据失败，状态码: ${listRes.status}`);
                }
                const invoices = await listRes.json();
                renderList(invoices);

                // 加载统计
                const statsRes = await fetch(`http://localhost:5000/stats?${params}`);
                if (!statsRes.ok) {
                    throw new Error(`请求统计数据失败，状态码: ${statsRes.status}`);
                }
                const stats = await statsRes.json();
                document.getElementById('totalCount').textContent = stats.total_count;
                document.getElementById('totalAmount').textContent = stats.total_amount.toFixed(2);
            } catch (error) {
                alert('数据加载失败');
                console.error(error);
            }
        }

        async function naturalLanguageQuery() {
            const naturalQuery = document.getElementById('naturalQuery').value;
            console.log('自然语言查询输入:', naturalQuery);
            const params = new URLSearchParams({
                query: naturalQuery
            });
            try {
                const response = await fetch(`http://localhost:5000/natural_query?${params}`);
                if (!response.ok) {
                    throw new Error(`请求失败，状态码: ${response.status}`);
                }
                try {
                    const invoices = await response.json();
                    if (invoices.length === 0) {
                        alert("未查询到符合条件的发票记录，请检查查询语句。");
                    } else {
                        renderList(invoices);
                    }
                    // 获取并更新统计信息
                    const statsRes = await fetch(`http://localhost:5000/stats?${params}`);
                    if (!statsRes.ok) {
                        throw new Error(`请求统计数据失败，状态码: ${statsRes.status}`);
                    }
                    const stats = await statsRes.json();
                    document.getElementById('totalCount').textContent = stats.total_count;
                    document.getElementById('totalAmount').textContent = stats.total_amount.toFixed(2);
                } catch (parseError) {
                    alert(`自然语言查询失败: 响应数据解析错误 - ${parseError.message}`);
                    console.error(parseError);
                }
            } catch (error) {
                alert(`自然语言查询失败: ${error.message}`);
                console.error(error);
            }
        }

        // 渲染列表
        function renderList(data) {
            console.log('接收到的数据:', data);
            const container = document.getElementById('resultList');
            container.innerHTML = data.map(item => {
                const amount = Number(item.amount);
                // 检查转换后的结果是否为有效的数字
                const formattedAmount = isNaN(amount) ? '未知' : amount.toFixed(2);
                return `
                    <div class="list-item" onclick="showImage('${item.image_url}')">
                        <div>发票代码：${item.invoice_code}</div>
                        <div>发票号码：${item.invoice_number}</div>
                        <div>日期：${item.date} 金额：¥${formattedAmount}</div>
                    </div>
                `;
            }).join('');
        }

        // 图片预览
        function showImage(url) {
            document.getElementById('previewImage').src = url;
            document.getElementById('previewModal').style.display = 'block';
        }

        function closePreview() {
            document.getElementById('previewModal').style.display = 'none';
        }

        // 初始化加载
        loadData();
    </script>
</body>

</html>